<?php
namespace App\Http\Middleware;


use App\Exception\TenantException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Db\Exception\DbException;
use Swoft\Http\Message\Request;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Contract\MiddlewareInterface;

/**
 * Class TenantMiddleware
 * @package App\Http\Middleware
 * @Bean("TenantMiddleware")
 */
class TenantMiddleware implements MiddlewareInterface
{

    /**
     * @inheritDoc
     * @throws TenantException
     * @throws DbException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 获取租户信息
        $tenant = getTenant();
        if (empty($tenant)) {
            // 抛出异常 定义错误码和错误提示 并填写到 TenantException 中
            throw new TenantException();
        }

        // 这里可以通过判断租户表查看租户得状态以及其他
        try {
            if(strtolower($tenant) <> 'admin' && !tenant_check($tenant)){
                throw new TenantException("租户状态不合法");
            }
        }
        catch (\Exception $e){
            throw new TenantException($e->getMessage());
        }


        // 传递 tenant 信息到控制器中
        return $handler->handle(
            $request->withAttribute('tenant', $tenant)
        );
    }
}
